package com.example.blog.controller;

import com.example.blog.common.LoginJudge;
import com.example.blog.entity.Blog;
import com.example.blog.entity.User;
import com.example.blog.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RequestMapping("/blog")
@Controller
public class BlogController {
    @Autowired
    private BlogService blogService;

    @ResponseBody
    @RequestMapping("/getAll")
    public List<Blog> selectAll() {
        List<Blog> list = blogService.selectAll();
        for (Blog blog : list) {
            if (blog.getContent().length() > 50) {
                blog.setContent(blog.getContent().substring(0,31) + "  ...... ");
            }
        }
        return list;
    }

    @ResponseBody
    @RequestMapping("/getById")
    public Blog selectById(Integer blogid) {
        if (blogid == null) return null;
        return blogService.selectById(blogid);
    }

    @RequestMapping("/add")
    @ResponseBody
    public Blog add(Blog blog,Integer blogid,HttpServletRequest req) {
        User user = LoginJudge.judge(req);
        if (user == null) return new Blog();
        // 表示是写博客
        if (blogid == null) {
            blog.setPosttime(LocalDateTime.now());
            blog.setUserid(user.getUserid());
            int result = blogService.add(blog);
            return blog;
        }else {
            // 表示改博客
            blog.setBlogid(blogid);
            blog.setPosttime(LocalDateTime.now());
            int result = blogService.upBlog(blog);
            return blog;
        }
    }

    @RequestMapping("/upblog")
    @ResponseBody
    public Blog upBlog(Integer blogid,HttpServletRequest req) {
        User user = LoginJudge.judge(req);
        if (user == null) return new Blog();
        // 如果博客id 不存在就说明进行的是 写博客 此时是不会获取数据给前端的
        if (blogService.selectById(blogid).getUserid() != user.getUserid()) {
            // 如果不是作者无法修改博客
            return new Blog();
        }
        return blogService.selectById(blogid);
    }

    @RequestMapping("/del")
    @ResponseBody
    public Blog delBlog(Integer blogid,HttpServletRequest req) {
        User user = LoginJudge.judge(req);
        if (user == null) return null;
        Blog blog1 = blogService.selectById(blogid);
        // 只有作者才能修改文章
        if (blog1.getUserid() != user.getUserid()) {
            return null;
        }
        blogService.delBlog(blogid);
        return blog1;
    }
}